/*
 * Copyright (c) 2010-2011 NOO. All Rights Reserved.
 * [Id:UserPasswordValidator.java  2011-10-27 上午12:17 poplar.yfyang ]
 */
package org.mumu.pawn.validator;

import org.jboss.seam.faces.validation.InputField;
import org.mumu.pawn.cmps.UserCmp;
import org.mumu.pawn.domain.User;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.inject.Inject;

/**
 * <p>
 * 用户 密码验证.
 * </p>
 *
 * @author poplar.yfyang
 * @version 1.0 2011-10-27 上午12:17
 * @since JDK 1.5
 */
@FacesValidator("confirmPwdValidator")
public class UserPasswordValidator implements Validator {
    /**
     * 用户组件服务
     */
    @Inject
    private UserCmp userCmp;
    /**
     * 由页面注入的用户名称
     */
    @Inject
    @InputField
    private String userName;
    /**
     * 页面注入的密码
     */
    @Inject
    @InputField
    private String password;
    /**
     * 页面注入的验证密码
     */
    @Inject
    @InputField
    private String confirmPassword;

    /**
     * 验证方法。
     *
     * @param context   JSF当前上下文
     * @param component 当前组件
     * @param value     数据
     * @throws ValidatorException 验证异常
     */
    @Override
    public void validate(final FacesContext context, final UIComponent component, final Object value) throws ValidatorException {
        if (password == null || confirmPassword == null) {
            return;
        }

        User user = userCmp.findUser(userName);
        if (user != null) {
            throw new ValidatorException(
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "用户名称已经存在!", "错误信息")
            );
        }
        if (!password.equals(confirmPassword)) {
            throw new ValidatorException(
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "密码与确认密码不一致!", "错误信息")
            );
        }
    }
}
